package com.yycx.generator.core;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import org.apache.commons.lang3.ObjectUtils;

import java.util.List;

/**
 * 代码生成工具类
 *
 * @author zyf
 */
public class GenerateUtils {
    /**
     * 计算table别名
     *
     * @param tableName
     * @return
     */
    public static String getAlias(String tableName) {
        String[] str = tableName.split("_");
        String alias = "";
        if (str.length > 2) {
            for (String s : str) {
                alias += s.substring(0, 1);
            }
        } else {
            alias = str[str.length - 1];
        }
        return alias;
    }


    /**
     * 计算包路径
     *
     * @param pc
     * @param name
     * @return
     */
    public static String getPackName(PackageConfig pc, String name) {
        String clientBasePath = pc.getParent() + "." + name;
        return "src/main/java/" + clientBasePath.replace(".", "/") + "/";
    }

    /**
     * 计算模块路径
     *
     * @param config
     * @return
     */
    public static String getModuleName(GenerateConfig config) {
        String path = "";
        if (ObjectUtils.isEmpty(config.getModuleName())) {
            path = "/" + config.getBaseModule() + "/" + config.getBaseModule();
        } else {
            path = "/" + config.getBaseModule() + "/" + config.getModuleName() + "/" + config.getModuleName();
        }
        return path;
    }

    /**
     * json 转lsit
     *
     * @param json
     * @param c
     * @return
     */
    public static <T> List<T> toList(String json, Class<T> c) {
        JSONArray jsonArray = JSONUtil.parseArray(json);
        return JSONUtil.toList(jsonArray, c);
    }
}
